package com.dcy;

import com.dcy.common.constant.CommonConstant;
import com.dcy.common.model.ResponseData;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author dcy
 */
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan(basePackages = {"com.dcy.security.auth.mapper"})
@RestController
public class DcyAuthServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(DcyAuthServerApplication.class, args);
    }

    @Autowired
    private TokenStore tokenStore;

    /**
     * 暴露Remote Token Services接口
     * 获取登录信息
     * 如果其它服务需要验证Token，则需要远程调用授权服务暴露的验证Token的API接口
     *
     * @return
     */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public ResponseData getUser() {
        String tokenValue = ((OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails()).getTokenValue();
        return ResponseData.success(tokenStore.readAccessToken(tokenValue).getAdditionalInformation().get(CommonConstant.USER_INFO));
    }

    /**
     * 获取OAuth用户信息
     *
     * @param user
     * @param request
     * @return
     */
    @RequestMapping(value = "/getOAuthDetails", method = RequestMethod.GET)
    public OAuth2Authentication getOAuthDetails(OAuth2Authentication user, HttpServletRequest request) {
        // Authentication
        return user;
    }
}
